<!DOCTYPE HTML>
<html lang="zh-CN">




<head>
    <meta charset="utf-8">
    <meta name="keywords" content="&#39;AndroidPart1&#39;, 深度学习 故障诊断 Java">
    <meta name="description" content="河海大学 | 计算机与信息学院 | 信号与信息处理">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>&#39;AndroidPart1&#39; | 世庆的博客</title>
    <link rel="icon" type="image/png" href="/shiqing/favicon.png">

    <link rel="stylesheet" type="text/css" href="/shiqing/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/my.css">

    <script src="/shiqing/libs/jquery/jquery.min.js"></script>

    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 6.3.0"></head>




    <body>
        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/shiqing/" class="waves-effect waves-light">
                    
                    <img src="/shiqing/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">世庆的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/shiqing/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">世庆的博客</div>
        <div class="logo-desc">
            
            河海大学 | 计算机与信息学院 | 信号与信息处理
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/sqtian-hhu/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/sqtian-hhu/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/shiqing/medias/featureimages/1.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">&#39;AndroidPart1&#39;</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/shiqing/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/shiqing/tags/%E5%AE%89%E5%8D%93%E5%BC%80%E5%8F%91/">
                                <span class="chip bg-color">安卓开发</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/shiqing/categories/%E5%AE%89%E5%8D%93/" class="post-category">
                                安卓
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-04-17
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/shiqing/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="第一个应用"><a href="#第一个应用" class="headerlink" title="第一个应用"></a>第一个应用</h2><p>public class MainActivity extends AppCompatActivity {</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() &#123;
        @Override
        public void onClick(View v) &#123;
            //当被点击时出发的行为
            Toast.makeText(MainActivity.this,&quot;爱你哦&quot;,Toast.LENGTH_LONG).show();
        &#125;
    &#125;);
&#125;
</code></pre>
<p>}</p>
<p>&#x3D;&gt; Buile APK</p>
<h2 id="产品提出了一些需求"><a href="#产品提出了一些需求" class="headerlink" title="产品提出了一些需求"></a>产品提出了一些需求</h2><h2 id="新建一个应用-有一个页面-版本号为1-0-0-D-ASWork-app-build-gradle中修改-versionCode-1-versionName-“1-0-0”-修改应用图标-D-ASWork-app-src-main-AndroidManifest-xml中修改android-icon-x3D-”-mipmap-x2F-ic-launcher”-首字母不可大写-添加启动界面"><a href="#新建一个应用-有一个页面-版本号为1-0-0-D-ASWork-app-build-gradle中修改-versionCode-1-versionName-“1-0-0”-修改应用图标-D-ASWork-app-src-main-AndroidManifest-xml中修改android-icon-x3D-”-mipmap-x2F-ic-launcher”-首字母不可大写-添加启动界面" class="headerlink" title="新建一个应用    有一个页面    版本号为1.0.0        D:\ASWork\app\build.gradle中修改            versionCode 1            versionName “1.0.0”    修改应用图标        D:\ASWork\app\src\main\AndroidManifest.xml中修改android:icon&#x3D;”@mipmap&#x2F;ic_launcher”        首字母不可大写    添加启动界面"></a>新建一个应用<br>    有一个页面<br>    版本号为1.0.0<br>        D:\ASWork\app\build.gradle中修改<br>            versionCode 1<br>            versionName “1.0.0”<br>    修改应用图标<br>        D:\ASWork\app\src\main\AndroidManifest.xml中修改android:icon&#x3D;”@mipmap&#x2F;ic_launcher”<br>        首字母不可大写<br>    添加启动界面</h2><?xml version="1.0" encoding="utf-8"?>
<p><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/splashBackgroundColor"
    android:gravity="center"></p>
<pre><code>&lt;TextView
    android:id=&quot;@+id/title_text_view&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;@string/splash_text&quot;
    android:textColor=&quot;@color/white&quot;
    android:textSize=&quot;24sp&quot;/&gt;

&lt;Button
    android:id=&quot;@+id/enter_button&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;@dimen/button_margin&quot;
    android:text=&quot;@string/click&quot;/&gt;
</code></pre>
</LinearLayout>	
--------------------------------------------------------------------	
    首页四个按钮,分别进入不同页面传递标题
        布局
        跳转
-------------------------------------------------------------------------		
public class SplashActivity extends Activity {

<pre><code>//定义按钮开关
private Button mEnterButton;
//定义点击触发事件
private View.OnClickListener mOnClickListener = new View.OnClickListener() &#123;
    @Override
    public void onClick(View v) &#123;
        switch (v.getId())&#123;
            case R.id.enter_button:
                Intent intent = new Intent(SplashActivity.this,MainActivity.class);
                startActivity(intent);
                break;
        &#125;
    &#125;
&#125;;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    mEnterButton = (Button)findViewById(R.id.enter_button);

    mEnterButton.setOnClickListener(mOnClickListener);
&#125;
</code></pre>
<h2 id=""><a href="#" class="headerlink" title="}"></a>}</h2><h2 id="Activity"><a href="#Activity" class="headerlink" title="Activity"></a>Activity</h2><p>在启动页面停留一秒自动进入下一个页面<br>public class SplashActivity extends Activity {<br>    Handler mHandler &#x3D; new Handler();<br>    @Override<br>    protected void onCreate(@Nullable Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_splash);</p>
<pre><code>    //延迟1000ms后跳转
    mHandler.postDelayed(new Runnable() &#123;
        @Override
        public void run() &#123;
            //跳转到MainActivity
            Intent intent = new Intent(SplashActivity.this,MainActivity.class);
            startActivity(intent);
        &#125;
    &#125;,1000);
&#125;
</code></pre>
<p>}</p>
<p>Activity间传递数据<br>SplashActivity<br>        &#x2F;&#x2F;获取到textView<br>        TextView textView &#x3D; (TextView) findViewById(R.id.title_text_view);<br>        final String title &#x3D; textView.getText().toString();</p>
<pre><code>    //延迟1000ms后跳转
    mHandler.postDelayed(new Runnable() &#123;
        @Override
        public void run() &#123;
            //跳转到MainActivity
            Intent intent = new Intent(SplashActivity.this,MainActivity.class);
            //把数据传递到下一个页面,先获取这个数据
            intent.putExtra(&quot;title&quot;,title);
            startActivity(intent);
        &#125;
    &#125;,1000);
</code></pre>
<hr>
<p>MainActivity<br>        &#x2F;&#x2F;接收数据,得到intent<br>        Intent intent &#x3D; getIntent();<br>        if (intent !&#x3D; null){<br>            String title &#x3D; intent.getStringExtra(“title”);<br>            setTitle(title);<br>        }</p>
<p>传递对象<br>&#x2F;&#x2F;对象需要序列化<br>public class UserInfo implements Serializable {<br>    private String mUserName;<br>    private Integer mAge;</p>
<pre><code>public UserInfo(String mUserName, Integer mAge) &#123;
    this.mUserName = mUserName;
    this.mAge = mAge;
&#125;
</code></pre>
<h2 id="-1"><a href="#-1" class="headerlink" title="}"></a>}</h2><p>SplashActivity<br>            @Override<br>            public void run() {</p>
<pre><code>            UserInfo userInfo = new UserInfo(&quot;CC&quot;,18);

            //跳转到MainActivity
            Intent intent = new Intent(SplashActivity.this,MainActivity.class);
            //把数据传递到下一个页面,先获取这个数据
            intent.putExtra(&quot;title&quot;,title);
            intent.putExtra(&quot;userInfo&quot;, userInfo);
            startActivity(intent);
        &#125;
</code></pre>
<hr>
<p>MainActivity<br>        &#x2F;&#x2F;接收数据,得到intent<br>        Intent intent &#x3D; getIntent();<br>        if (intent !&#x3D; null){<br>            String title &#x3D; intent.getStringExtra(“title”);</p>
<pre><code>        //接收序列化之后的对象
        UserInfo userInfo = (UserInfo) intent.getSerializableExtra(&quot;userInfo&quot;);
        setTitle(userInfo.getmUserName());
    &#125;
</code></pre>
<hr>
<p>小问题：<br>intent.putExtra(“title”,title);<br>intent.putExtra(“userInfo”, userInfo);<br>将”title”，”userInfo”提取成常量，方便修改代码，ctrl+alt+C<br>    public static final String TITLE &#x3D; “title”;<br>    public static final String USER_INFO &#x3D; “userInfo”;</p>
<p>获取数据时，传递引用的常量<br>        &#x2F;&#x2F;接收数据,得到intent<br>        Intent intent &#x3D; getIntent();<br>        if (intent !&#x3D; null){<br>            String title &#x3D; intent.getStringExtra(SplashActivity.TITLE);</p>
<pre><code>        //接收序列化之后的对象
        UserInfo userInfo = (UserInfo) intent.getSerializableExtra(SplashActivity.USER_INFO);
        setTitle(userInfo.getmUserName());
    &#125;
    
</code></pre>
<p>&#x2F;&#x2F;ctrl+alt+F 快捷设置全局变量		</p>
<p>Activity回传数据</p>
<p>SplashActivity<br>&#x2F;&#x2F;              startActivity(intent);<br>                &#x2F;&#x2F;传递出去再接收回传数据<br>                startActivityForResult(intent, REQUEST_CODE);</p>
<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) &#123;
    super.onActivityResult(requestCode, resultCode, data);
    Log.i(TAG,&quot;requestCode:&quot;+requestCode+&quot;,resultCode:&quot;+resultCode);
    //04-09 03:56:47.971 4435-4435/com.example.sqtian I/SplashActivity: requestCode:9999,resultCode:1234
    //判断链接页面是否正确
    if(requestCode==REQUEST_CODE&amp;&amp;resultCode==MainActivity.RESULT_CODE)&#123;
        if(data != null)&#123;
            String title = data.getStringExtra(TITLE);
            mTextView.setText(title);
        &#125;
    &#125;

&#125;
</code></pre>
<hr>
<p>MainActivity<br>        findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                Intent intent &#x3D; new Intent();<br>                intent.putExtra(SplashActivity.TITLE,”我是主页,我送礼回来了”);<br>                setResult(RESULT_CODE,intent);<br>                finish();<br>            }<br>        });</p>
<h2 id="Activity的生命周期"><a href="#Activity的生命周期" class="headerlink" title="Activity的生命周期"></a>Activity的生命周期</h2><p>onCreate()<br>onStart()<br>onResume()<br>onPause()<br>onStop()<br>onDestroy()<br>onRestart()<br>    @Override<br>    protected void onStart() {<br>        super.onStart();<br>        Log.i(TAG,”onStart”);<br>    }</p>
<pre><code>@Override
protected void onResume() &#123;
    super.onResume();
    Log.i(TAG,&quot;onResume&quot;);
&#125;

@Override
protected void onPause() &#123;
    super.onPause();
    Log.i(TAG,&quot;onPause&quot;);
&#125;

@Override
protected void onStop() &#123;
    super.onStop();
    Log.i(TAG,&quot;onStop&quot;);
&#125;

@Override
protected void onDestroy() &#123;
    super.onDestroy();
    Log.i(TAG,&quot;onDestroy&quot;);
&#125;

@Override
protected void onRestart() &#123;
    super.onRestart();
    Log.i(TAG,&quot;onRestart&quot;);
&#125;
</code></pre>
<h2 id="控件"><a href="#控件" class="headerlink" title="控件"></a>控件</h2><p>控件View的通用属性:宽高, 颜色, 边距, 是否可见, 内容居中, 点击事件</p>
<p>TextView 显示文本 CheckedTextView</p>
<p>EditText 编辑框 hint password lines singlines maxlines<br>phoneNumber等</p>
<p>Button 点击按钮 .9图</p>
<p>ImageButton 图片按钮 extends ImageView</p>
<p>ImageView 图片视图<br>    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/cc_background"
        android:scaleType="center"
        app:srcCompat="@mipmap/cc1" /></p>
<p>滑动条<br>    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        /></p>
<p>进度条<br>    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"/></p>
<p>WebView：加载网页<br>ListView：显示列表<br>GridView：显示表格式列表<br>ScrollView：内容可滚动视图<br>SufaceView：非常重要的绘图容器</p>
<h2 id="Android开发布局详解"><a href="#Android开发布局详解" class="headerlink" title="Android开发布局详解"></a>Android开发布局详解</h2><p>五大布局<br>线性布局：LinearLayout<br>&lt;LinearLayout<br>android:orientation&#x3D;”vertical” 垂直或者水平<br>&lt;TextView<br>android:layout_weight&#x3D;”1” 设置占屏幕比重<br>相对布局：RelativeLayout<br>android:layout_alignParentRight&#x3D;”true” 在页面右边<br>android:layout_above&#x3D;”@+id&#x2F;button” 在button的上面<br>android:layout_toRightOf&#x3D;”@+id&#x2F;button” 在button的右面<br>android:layout_alignTop&#x3D;”@+id&#x2F;button” 与button上边缘对齐<br>android:layout_marginLeft&#x3D;”100dp” 距离左边界100dp<br>android:paddingLeft&#x3D;”40dp” 内部文字距离边框40dp</p>
<p>帧布局：FrameLayout<br>可重叠</p>
<p>绝对布局：AbsoluteLayout<br>表格布局：TableLayout</p>
<p>布局技巧与优化<br>官方建议布局层次 10层<br>利用相对布局，尽量减少布局层次</p>
<p>布局引用相同部分<br>    <include layout="@layout/activity_splash"/><br>减少视图层级<br><merge/><br>需要时才加载<br><ViewStub/></p>
<p>总结:如何优化布局</p>
<ol>
<li>减少层次</li>
<li>删除无用布局</li>
<li>布局结构要清晰</li>
<li>选择合适的布局<br>小技巧:</li>
<li>不要嵌套多个使用layout_weight属性的LinearLayout</li>
<li>Android lint</li>
<li>HierarchyViewer</li>
</ol>
<h2 id="无比重要的ListView"><a href="#无比重要的ListView" class="headerlink" title="无比重要的ListView"></a>无比重要的ListView</h2><p>常用属性：<br>    listSelector<br>    scrollingCache<br>    cacheColorHint<br>    fastScrollEnabled<br>    ……<br>常用方法<br>    addHeaderView<br>    addFooterView</p>
<ol>
<li>设置ListView视图 activity_listview_demo.xml,list_view呈现列表数据</li>
<li>ListViewDemoActivity中获得list_view,利用phoneBookAdapter将数据与视图绑定</li>
<li>phoneBookAdapter继承BaseAdapter,getView方法返回视图</li>
<li>mLayoutInflater.inflate(R.layout.item_phone_book_friend, null)将页面解析为视图</li>
<li>从解析的视图中获取TextView控键,和数据进行绑定</li>
</ol>
<p>public class ListViewDemoActivity extends Activity {</p>
<pre><code>//ListView视图作为一个容器，房子
private ListView mphoneBookListView;
private List&lt;UserInfo&gt; mUserInfos;

@Override
protected void onCreate(Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listview_demo);
    mphoneBookListView = (ListView)findViewById(R.id.list_view);
    mUserInfos = new ArrayList&lt;&gt;();
    mUserInfos.add(new UserInfo(&quot;西门吹雪&quot;, 18));
    mUserInfos.add(new UserInfo(&quot;李寻欢&quot;, 17));
    mUserInfos.add(new UserInfo(&quot;楚留香&quot;, 20));
    mUserInfos.add(new UserInfo(&quot;陆小凤&quot;, 19));



    //数据列表和数据绑定,adapter适配器，房子里的柜子，柜子放进房子
    final PhoneBookAdapter phoneBookAdapter = new PhoneBookAdapter(ListViewDemoActivity.this, mUserInfos);
    //房子(mphoneBookListView)里面有柜子(phoneBookAdapter)，柜子里面有格子(name_text_view)，
    //格子里面放数据private String[] mNames = &#123;&quot;西门吹雪&quot;,&quot;李寻欢&quot;&#125;
    mphoneBookListView.setAdapter(phoneBookAdapter);

    //刷新更新数据
    phoneBookAdapter.notifyDataSetChanged();
    //条目点击事件
    mphoneBookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() &#123;
        @Override
        public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) &#123;
            //点击第一条数据时更新
            if(position==0)&#123;
                // 新建另外一批数据
                mUserInfos.clear();
                mUserInfos.add(new UserInfo(&quot;我是新数据一&quot;,20));
                mUserInfos.add(new UserInfo(&quot;我是新数据二&quot;,20));
                mUserInfos.add(new UserInfo(&quot;我是新数据三&quot;,20));
                // 替换掉老的数据,数据通过PhoneBookAdapter传递,因此要在PhoneBookAdapter中创建refreshData方法
                // 刷新ListView,让他更新自己的视图
                phoneBookAdapter.refreshData(mUserInfos);
            &#125;


            Toast.makeText(ListViewDemoActivity.this, mUserInfos.get(position).getmUserName()+&quot;被点击了&quot;,Toast.LENGTH_LONG).show();
        &#125;
    &#125;);
    //长按事件
    mphoneBookListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() &#123;
        @Override
        public boolean onItemLongClick(AdapterView&lt;?&gt; parent, View view, int position, long id) &#123;
            Toast.makeText(ListViewDemoActivity.this, mUserInfos.get(position).getmUserName()+&quot;被长按了&quot;,Toast.LENGTH_LONG).show();
            return false;
        &#125;
    &#125;);

&#125;
</code></pre>
<h2 id="-2"><a href="#-2" class="headerlink" title="}"></a>}</h2><p>D:\ASWork\app\src\main\res\layout\activity_listview_demo.xml<br>    <TextView
        android:id="@+id/phone_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/phone_book"/></p>
<pre><code>&lt;ListView
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:layout_below=&quot;@+id/phone_text_view&quot;
    android:id=&quot;@+id/list_view&quot;/&gt;
    
</code></pre>
<hr>
<p>public class PhoneBookAdapter extends BaseAdapter {</p>
<pre><code>private Context mcontext;
//解析layout
private LayoutInflater mLayoutInflater;

private List&lt;UserInfo&gt; mUserinfos = new ArrayList&lt;&gt;();


public PhoneBookAdapter(Context mcontext, List&lt;UserInfo&gt; userInfos) &#123;
    this.mcontext = mcontext;
    this.mUserinfos = userInfos;
    this.mLayoutInflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
&#125;

@Override
public int getCount() &#123;
    // 有多少条数据
    return mUserinfos.size();
&#125;

@Override
public Object getItem(int position) &#123;
    //返回某一条数据对象
    return mUserinfos.get(position);
&#125;

@Override
public long getItemId(int position) &#123;

    return position;
&#125;

/**
 * 每一行数据显示在界面,用户能够看到,就会调用一次geiView
 * @param position
 * @param convertView
 * @param parent
 * @return
 */
@Override
public View getView(int position, View convertView, ViewGroup parent) &#123;
    //返回一个视图, 柜子很多层，把数据塞进柜子，item_phone_book_friend

    ViewHolder viewHolder;
    //空则创建,非空则直接使用,提高代码复用率
    if(convertView == null)&#123;
        convertView = mLayoutInflater.inflate(R.layout.item_phone_book_friend, null);
        viewHolder = new ViewHolder();
        //把viewHolder存到convertView里
        convertView.setTag(viewHolder);


        //把名字数据塞进name_text_view
        //从实现保存的ViewHolder中获取控件
        viewHolder.nameTextView     = (TextView) convertView.findViewById(R.id.name_text_view);
        viewHolder.ageTextView      = (TextView) convertView.findViewById(R.id.age_text_view);
        viewHolder.avatarImageView = (ImageView) convertView.findViewById(R.id.avatar_image_view);
    &#125;else&#123;
        viewHolder = (ViewHolder)convertView.getTag();
    &#125;

    //和数据进行绑定
    viewHolder.nameTextView.setText(mUserinfos.get(position).getmUserName());
    viewHolder.ageTextView.setText(mUserinfos.get(position).getmAge()+&quot;岁&quot;);
    viewHolder.avatarImageView.setImageResource(R.drawable.cc1);


    return convertView;


&#125;
//定义一个类把视图先保存起来
class ViewHolder&#123;
    TextView nameTextView;
    TextView ageTextView;
    ImageView avatarImageView;
&#125;

public void refreshData(List&lt;UserInfo&gt; userInfos)&#123;
    //刷新数据
    mUserinfos = userInfos;
    //刷新视图
    notifyDataSetChanged();
&#125;
</code></pre>
<p>}</p>
<hr>
<p>D:\ASWork\app\src\main\res\layout\item_phone_book_friend.xml<br>    <ImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/avatar_image_view"/></p>
<pre><code>&lt;TextView
    android:id=&quot;@+id/name_text_view&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;6dp&quot;
    android:layout_toRightOf=&quot;@+id/avatar_image_view&quot;
    android:text=&quot;呈呈&quot; /&gt;

&lt;TextView
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;18岁&quot;
    android:layout_toRightOf=&quot;@+id/avatar_image_view&quot;
    android:layout_below=&quot;@+id/name_text_view&quot;
    android:id=&quot;@+id/age_text_view&quot;/&gt;
    
</code></pre>
<hr>
<h2 id="GridView"><a href="#GridView" class="headerlink" title="GridView"></a>GridView</h2><p>显示表格式列表<br>与ListView的相似之处和区别<br>相似之处：<br>    GridView extends AbsListView<br>    ListView extends AbsListView<br>    adapter，数据，点击事件，刷新都一样<br>不同之处：<br>    样式（宫格式）</p>
<pre><code>&lt;GridView
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:numColumns=&quot;auto_fit&quot;
    android:horizontalSpacing=&quot;10dp&quot;
    android:verticalSpacing=&quot;10dp&quot;
    android:id=&quot;@+id/grid_view&quot;/&gt;
    
</code></pre>
<h2 id="ScrollView"><a href="#ScrollView" class="headerlink" title="ScrollView"></a>ScrollView</h2><p>内容可滚动视图<br>不是列表的内容区滚动<br>只支持垂直滚动<br>里面只能由一个视图<br>    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/grid_view_button"
        android:layout_centerHorizontal="true"><br>        <LinearLayout
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:orientation="vertical"></p>
<pre><code>        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;

            android:text=&quot;我是来自于ScrollView中的&quot;/&gt;
        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;我是来自于ScrollView中的&quot;/&gt;
        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;我是来自于ScrollView中的&quot;/&gt;
        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;我是来自于ScrollView中的&quot;/&gt;
        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;我是来自于ScrollView中的&quot;/&gt;
    &lt;/LinearLayout&gt;
&lt;/ScrollView&gt;
</code></pre>
<h2 id="自定义控件"><a href="#自定义控件" class="headerlink" title="自定义控件"></a>自定义控件</h2><p>px：像素点<br>dp：与像素密度密切相关<br>sp：相当于dp（用来修饰文字）<br>dip：&#x3D;dp</p>
<p>文字的尺寸一律用sp单位<br>非文字的尺寸一律使用dp单位<br>偶尔需要使用px单位：例如需要在屏幕上画一条细的分割线：1px</p>
<p>LayoutInflater：将xml布局解析成实际的视图View</p>
<p>获得LayoutInflater实例的三种方式：<br>        mLayoutInflater &#x3D; getLayoutInflater();<br>        mLayoutInflater &#x3D; (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);<br>        mLayoutInflater &#x3D; LayoutInflater.from(MainActivity.this);</p>
<pre><code>    View view = mLayoutInflater.inflate(R.layout.activity_main,null);
</code></pre>
<p>提取布局属性：theme&amp;style<br>    Theme是针对窗体级别的，改变窗体样式<br>    Style是针对窗体元素级别的，改变指定控件或者Layout的样式<br>    抽象view的共同属性<br>    可继承</p>
<pre><code>&lt;style name=&quot;CustomTextView&quot;&gt;
    &lt;item name=&quot;android:background&quot;&gt;@color/blue&lt;/item&gt;
    &lt;item name=&quot;android:textSize&quot;&gt;20sp&lt;/item&gt;
    &lt;item name=&quot;android:textColor&quot;&gt;#FF5722&lt;/item&gt;
&lt;/style&gt;

&lt;style name=&quot;StudyTextView&quot; parent=&quot;CustomTextView&quot;&gt;
    &lt;item name=&quot;android:gravity&quot;&gt;right&lt;/item&gt;
&lt;/style&gt;
</code></pre>
<h2 id="View如何工作"><a href="#View如何工作" class="headerlink" title="View如何工作"></a>View如何工作</h2><p>构造器-&gt;初始化<br>onMesure() 定大小<br>onLayout() 定位置<br>onDraw() 绘制<br>invalidate() 刷新</p>
<p>自定义控件的三种主要形式</p>
<ol>
<li>继承已有的控件来实现自定义控件 如Button extends TextView</li>
<li>继承一个布局文件实现 如RelativeLayout</li>
<li>通过view类来实现</li>
</ol>
<p>	</p>
<p>练习 需求:<br>    1. 做一个圆形的红色按钮<br>    2. 中间有一个白色的数字<br>    3. 数字起始为20<br>    4. 每点击一次减少1</p>
<hr>
<p>D:\ASWork\app\src\main\java\com\example\sqtian\TestRedButton.java</p>
<p>&#x2F;**</p>
<ul>
<li>自定义控件</li>
<li><pre><code>1. 做一个圆形的红色按钮
</code></pre>
</li>
<li><pre><code>2. 中间有一个白色的数字
</code></pre>
</li>
<li><pre><code>3. 数字起始为20
</code></pre>
</li>
<li><pre><code>4. 每点击一次减少1
</code></pre>
</li>
<li>author ：HASEE</li>
<li>date : 2020&#x2F;4&#x2F;13 10:20</li>
<li>package：com.example.sqtian</li>
<li>description :<br> *&#x2F;</li>
</ul>
<p>public class TestRedButton extends View implements View.OnClickListener {</p>
<pre><code>private Paint mPaint;
private Rect mRect;
private int mNumber = 20;

private int mBackgroundColor;
private int mTextSize;
private int mTextColor;


public TestRedButton(Context context) &#123;
    this(context,null,0);
&#125;

public TestRedButton(Context context, @Nullable AttributeSet attrs) &#123;
    this(context, attrs,0);
&#125;

public TestRedButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) &#123;
    super(context, attrs, defStyleAttr);
    init(context,attrs);
&#125;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public TestRedButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) &#123;
    super(context, attrs, defStyleAttr, defStyleRes);
    init(context, attrs);
&#125;



//绘制
@Override
protected void onDraw(Canvas canvas) &#123;
    super.onDraw(canvas);
    //给画布设置颜色
</code></pre>
<p>&#x2F;&#x2F;        mPaint.setColor(Color.RED);<br>        mPaint.setColor(mBackgroundColor);<br>        &#x2F;&#x2F;canvas画图，画一个圆<br>        canvas.drawCircle(getWidth()&#x2F;2,getHeight()&#x2F;2,getWidth()&#x2F;2 ,mPaint);<br>        &#x2F;&#x2F;中间有白色数字<br>        mPaint.setColor(mTextColor);<br>        mPaint.setTextSize(mTextSize);<br>        String text &#x3D; String.valueOf(mNumber);<br>        &#x2F;&#x2F;文字边距,起始0,结束text.length()<br>        mPaint.getTextBounds(text,0,text.length(),mRect);<br>        int textWedth &#x3D; mRect.width();<br>        int textHeight &#x3D; mRect.height();</p>
<pre><code>    //把文字画在圆圈中间
    canvas.drawText(text,getWidth()/2-textWedth/2,getHeight()/2+textHeight/2,mPaint);

&#125;

//初始化
private void init(Context context,AttributeSet attrs) &#123;
    //画布
    mPaint = new Paint();
    //创建一个新的空矩形
    mRect = new Rect();
    //点击监听
    this.setOnClickListener(this);

    //获取自定义的属性
    @SuppressLint(&quot;Recycle&quot;) TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TestRedButton);
    mBackgroundColor = typedArray.getColor(R.styleable.TestRedButton_backgroundColor, Color.RED);
    mTextSize = typedArray.getDimensionPixelSize(R.styleable.TestRedButton_textSize,18);//接收dp
    mTextColor = typedArray.getColor(R.styleable.TestRedButton_textColor,Color.WHITE);

&#125;

@Override
public void onClick(View v) &#123;
    //每点击一次减少一
    if(mNumber&gt;0)&#123;
        mNumber--;

    &#125;else&#123;
        mNumber = 20;
    &#125;
    //刷新界面
    invalidate();


&#125;
</code></pre>
<h2 id="-3"><a href="#-3" class="headerlink" title="}"></a>}</h2><p>D:\ASWork\app\src\main\res\layout\activity_test_red_button.xml</p>
<p><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></p>
<pre><code>&lt;com.example.sqtian.TestRedButton
    android:layout_width=&quot;300dp&quot;
    android:layout_height=&quot;300dp&quot;
    app:backgroundColor=&quot;@color/blue&quot;
    app:textColor=&quot;@color/splashBackgroundColor&quot;
    app:textSize=&quot;100sp&quot;/&gt;
</code></pre>
</LinearLayout>

<hr>
<p>D:\ASWork\app\src\main\java\com\example\sqtian\TestViewButtonActivity.java</p>
<p>public class TestViewButtonActivity extends Activity {<br>    @Override<br>    public void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_test_red_button);<br>    }<br>}</p>
<hr>
<p>如何自定义视图属性<br>在哪里创建属性: values中新建源文件<br>可以创建哪些属性<br>D:\ASWork\app\src\main\res\values\attrs.xml</p>
<resources>

<pre><code>&lt;declare-styleable name=&quot;TestRedButton&quot;&gt;
    &lt;attr name=&quot;backgroundColor&quot; format=&quot;color&quot;/&gt;
    &lt;attr name=&quot;textSize&quot; format=&quot;dimension&quot;/&gt;
    &lt;attr name=&quot;textColor&quot; format=&quot;color&quot;/&gt;
&lt;/declare-styleable&gt;
</code></pre>
</resources>
-----------------------------------------------------------
如何使用这些属性
    代码中引用
    布局中设置
    
<hr>
<pre><code>    //获取自定义的属性
    @SuppressLint(&quot;Recycle&quot;) TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TestRedButton);
    mBackgroundColor = typedArray.getColor(R.styleable.TestRedButton_backgroundColor, Color.RED);
    mTextSize = typedArray.getDimensionPixelSize(R.styleable.TestRedButton_textSize,18);//接收dp
    mTextColor = typedArray.getColor(R.styleable.TestRedButton_textColor,Color.WHITE);
</code></pre>
<hr>
<h2 id="使用Fragment"><a href="#使用Fragment" class="headerlink" title="使用Fragment"></a>使用Fragment</h2><p>Fragment是activity的界面中的一部分<br>多个Fragment组合到一个activity中<br>多个activity中可重用一个Fragment</p>
<h2 id="activity大房子-Fragment小房间总结-Fragment是activity相当于模块化的一段activity-具有自己的生命周期-接收自己的事件-在activity运行时被添加或删除使用-1-Create-Fragment-onCreate-onCreateView-onPause-2-Add-Fragment-Java-Code-Layout-3-Replace-Fragment在使用fragment的时候-先创建了一个fragment-然后为他创建布局-并在oncreateview中返回载入该视图的后返回的view-在activity的布局文件里-使用xml布局-用fragment的name标签直接引用这个fragment-然后居然爆出来该类不是fragment的错误-表示非常不理解-然后把原来fragment换成android-app-fragment就没有这些问题-于是问题也就慢慢的浮出水面-xml中载入的fragment是使用的android-app-fragment-假设我们的fragment引用的是v4包里面的-就会遇到该类不是fragment的问题-解决的办法要么是全都引用android-app-fragment里面的fragment-否则就使用动态载入的方法去载入该fragment-over-问题记录完成"><a href="#activity大房子-Fragment小房间总结-Fragment是activity相当于模块化的一段activity-具有自己的生命周期-接收自己的事件-在activity运行时被添加或删除使用-1-Create-Fragment-onCreate-onCreateView-onPause-2-Add-Fragment-Java-Code-Layout-3-Replace-Fragment在使用fragment的时候-先创建了一个fragment-然后为他创建布局-并在oncreateview中返回载入该视图的后返回的view-在activity的布局文件里-使用xml布局-用fragment的name标签直接引用这个fragment-然后居然爆出来该类不是fragment的错误-表示非常不理解-然后把原来fragment换成android-app-fragment就没有这些问题-于是问题也就慢慢的浮出水面-xml中载入的fragment是使用的android-app-fragment-假设我们的fragment引用的是v4包里面的-就会遇到该类不是fragment的问题-解决的办法要么是全都引用android-app-fragment里面的fragment-否则就使用动态载入的方法去载入该fragment-over-问题记录完成" class="headerlink" title="activity大房子,Fragment小房间总结:    Fragment是activity相当于模块化的一段activity    具有自己的生命周期,接收自己的事件    在activity运行时被添加或删除使用:    1. Create Fragment        onCreate()        onCreateView()        onPause()    2. Add Fragment        Java Code        Layout    3. Replace Fragment在使用fragment的时候,先创建了一个fragment,然后为他创建布局,并在oncreateview中返回载入该视图的后返回的view,在activity的布局文件里,使用xml布局,用fragment的name标签直接引用这个fragment,然后居然爆出来该类不是fragment的错误,表示非常不理解,然后把原来fragment换成android.app.fragment就没有这些问题,于是问题也就慢慢的浮出水面,xml中载入的fragment是使用的android.app.fragment,假设我们的fragment引用的是v4包里面的,就会遇到该类不是fragment的问题.解决的办法要么是全都引用android.app.fragment里面的fragment,否则就使用动态载入的方法去载入该fragment,over,问题记录完成
    "></a>activity大房子,Fragment小房间<br>总结:<br>    Fragment是activity相当于模块化的一段activity<br>    具有自己的生命周期,接收自己的事件<br>    在activity运行时被添加或删除<br><br>使用:<br>    1. Create Fragment<br>        onCreate()<br>        onCreateView()<br>        onPause()<br>    2. Add Fragment<br>        Java Code<br>        Layout<br>    3. Replace Fragment<br><br>在使用fragment的时候,先创建了一个fragment,然后为他创建布局,<br>并在oncreateview中返回载入该视图的后返回的view,<br>在activity的布局文件里,使用xml布局,用fragment的name标签直接引用这个fragment,<br>然后居然爆出来该类不是fragment的错误,表示非常不理解,<br>然后把原来fragment换成android.app.fragment就没有这些问题,<br>于是问题也就慢慢的浮出水面,xml中载入的fragment是使用的android.app.fragment,<br>假设我们的fragment引用的是v4包里面的,就会遇到该类不是fragment的问题.<br>解决的办法要么是全都引用android.app.fragment里面的fragment,<br>否则就使用动态载入的方法去载入该fragment,over,问题记录完成
    </h2><p>D:\ASWork\app\src\main\java\com\example\sqtian\TestFragment.java</p>
<p>&#x2F;&#x2F;需要继承android.app.Fragment<br>public class TestFragment extends android.app.Fragment {</p>
<pre><code>private static final String TAG = TestFragment.class.getSimpleName();
public static final String ARGUMENT_NAME = &quot;argument_name&quot;;
public static final String ARGUMENT_NUMBER = &quot;argument_number&quot;;
private int mNumber;
private String mName;

//传递参数进去
public static TestFragment newInstance(String nameString,int number)&#123;
    TestFragment testFragment = new TestFragment();

    //传递参数
    Bundle bundle = new Bundle();
    bundle.putString(ARGUMENT_NAME,nameString);
    bundle.putInt(ARGUMENT_NUMBER,number);
    testFragment.setArguments(bundle);
    return testFragment;
&#125;

@Override
public void onCreate(Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    Log.i(TAG,&quot;onCreate&quot;);

    //获取参数,抽取成全局变量,在onCreateView中就可以直接使用了
    Bundle bundle = getArguments();
    if(bundle != null)&#123;
        mName = bundle.getString(ARGUMENT_NAME);
        mNumber = bundle.getInt(ARGUMENT_NUMBER);
    &#125;
&#125;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) &#123;
    Log.i(TAG,&quot;onCreateView&quot;);
    View view = inflater.inflate(R.layout.item_phone_book_friend,container,false);
    //把页面中的控件拿出来
    TextView nameTextView = (TextView) view.findViewById(R.id.name_text_view);
    nameTextView.setText(mName);

    return view;
&#125;
</code></pre>
<h2 id="-4"><a href="#-4" class="headerlink" title="}"></a>}</h2><p>布局使用item_phone_book_friend</p>
<hr>
<p>public class TestFragmentActivity extends Activity {<br>    @Override<br>    public void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        &#x2F;&#x2F;1. 通过界面添加<br>        setContentView(R.layout.activity_test_fragment);</p>
<pre><code>    //2. 通过代码添加
    // 获取管理器
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    // 创建一个fragment对象实例
    TestFragment testFragment =  TestFragment.newInstance(&quot;Fragment&quot;,15);
    //需要传递一个ViewGroup,将其添加到ViewGroup
    fragmentTransaction.add(R.id.fragment_view,testFragment).commit();


&#125;
</code></pre>
<h2 id="-5"><a href="#-5" class="headerlink" title="}"></a>}</h2><p>D:\ASWork\app\src\main\res\layout\activity_test_fragment.xml</p>
<p><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"></p>
<pre><code>&lt;fragment
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;100dp&quot;
    android:name=&quot;com.example.sqtian.TestFragment&quot;
    android:id=&quot;@+id/fragment_test&quot;/&gt;

&lt;RelativeLayout
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;400dp&quot;
    android:layout_marginTop=&quot;200dp&quot;
    android:background=&quot;@color/white&quot;
    android:id=&quot;@+id/fragment_view&quot;&gt;

&lt;/RelativeLayout&gt;
</code></pre>
</RelativeLayout>

<hr>
<h2 id="Handler"><a href="#Handler" class="headerlink" title="Handler"></a>Handler</h2><p>多线程与异步</p>
<p>什么是Handler<br>发送处理Message和Runnable</p>
<p>用来做什么<br>定时执行Message和MessageQueue<br>在不同线程中执行</p>
<p>Message和MessageQueue<br>Message<br>2个整形数值：轻量级存储int类型的数据<br>一个Object：任意对象<br>replyTo：线程通信的时候使用<br>What：用户自定义的消息码让接收者识别消息</p>
<p>MessageQueue<br>Message的队列<br>每一个线程最多只可以拥有一个<br>Thread-&gt;Looper-&gt;MessageQueue</p>
<p>Lopper<br>消息泵<br>是MessageQueue的管理者<br>Looper.prepare()<br>每一个Looper对象和一个线程关联<br>Looper.myLooper()可以获得当前线程的Looper对象<br>Looper从MessageQueue中取出Message<br>交由Handler的handleMessage进行处理<br>调用Message.recycle()将其放入Message Pool中</p>
<p>实践:<br>倒计时功能<br>public class HandlerActivity extends Activity {</p>
<pre><code>public static final int MESSAGE_CODE = 888888;
</code></pre>
<p>&#x2F;&#x2F;    &#x2F;&#x2F;先创建一个Handler<br>&#x2F;&#x2F;    &#x2F;&#x2F;直接使用Handler内部类容易出现内存泄漏<br>&#x2F;&#x2F;    Handler mHandler &#x3D; new Handler(){<br>&#x2F;&#x2F;        &#x2F;&#x2F;重写接收消息的方法<br>&#x2F;&#x2F;        @Override<br>&#x2F;&#x2F;        public void handleMessage(@NonNull Message msg) {<br>&#x2F;&#x2F;            super.handleMessage(msg);<br>&#x2F;&#x2F;            &#x2F;&#x2F;接收消息<br>&#x2F;&#x2F;            switch(msg.what){<br>&#x2F;&#x2F;                case MESSAGE_CODE:<br>&#x2F;&#x2F;                    int value &#x3D; (int) msg.obj;<br>&#x2F;&#x2F;                    mTextView.setText(String.valueOf(value&#x2F;1000));<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;                    &#x2F;&#x2F;正在使用的message无法再用,重新创建一个msg<br>&#x2F;&#x2F;                    msg &#x3D; Message.obtain();<br>&#x2F;&#x2F;                    msg.arg1 &#x3D; 0;<br>&#x2F;&#x2F;                    msg.arg2 &#x3D; 1;<br>&#x2F;&#x2F;                    msg.what &#x3D; MESSAGE_CODE;<br>&#x2F;&#x2F;                    &#x2F;&#x2F;倒计时,每次-1s<br>&#x2F;&#x2F;                    msg.obj &#x3D; value-1000;<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;                    if(value &gt; 0){<br>&#x2F;&#x2F;                        &#x2F;&#x2F;大于0时继续倒计时,循环发送消息<br>&#x2F;&#x2F;                        sendMessageDelayed(msg,1000);<br>&#x2F;&#x2F;                    }<br>&#x2F;&#x2F;                    break;<br>&#x2F;&#x2F;            }<br>&#x2F;&#x2F;        }<br>&#x2F;&#x2F;    };<br>    private TextView mTextView;<br>    private TestHandler mTestHandler &#x3D; new TestHandler(this);</p>
<pre><code>//
public TextView getTextView() &#123;
    return mTextView;
&#125;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handler);

    mTextView = (TextView) findViewById(R.id.handler_text_view);

    //创建一个Message
    Message message = mTestHandler.obtainMessage();

    message.arg1 = 0;
    message.arg2 = 1;
    //消息识别码
    message.what = MESSAGE_CODE;
    //传递对象
    message.obj = 10000;
    //发送消息,延迟一秒
</code></pre>
<p>&#x2F;&#x2F;        mHandler.sendMessageDelayed(message,1000);<br>        &#x2F;&#x2F;用外部类发送<br>        mTestHandler.sendMessageDelayed(message,1000);</p>
<pre><code>    //handler还可以定时,延时
    mTestHandler.postDelayed(new Runnable() &#123;
        @Override
        public void run() &#123;

        &#125;
    &#125;,1000);


&#125;

//用外部类解决内存泄漏问题,继承Handler,activity销毁后,这个类也会自动结束
public  static class TestHandler extends Handler&#123;
    //弱引用HandlerActivity
     public final WeakReference&lt;HandlerActivity&gt; mHandlerActivityWeakReference;

    public TestHandler(HandlerActivity activity) &#123;

        mHandlerActivityWeakReference = new WeakReference&lt;&gt;(activity);
    &#125;

    @Override
    public void handleMessage(@NonNull Message msg) &#123;
        super.handleMessage(msg);

        HandlerActivity handlerActivity = mHandlerActivityWeakReference.get();

        //接收消息
        switch(msg.what)&#123;
            case MESSAGE_CODE:
                int value = (int) msg.obj;
                handlerActivity.getTextView().setText(String.valueOf(value/1000));

                //正在使用的message无法再用,重新创建一个msg
                msg = Message.obtain();
                msg.arg1 = 0;
                msg.arg2 = 1;
                msg.what = MESSAGE_CODE;
                //倒计时,每次-1s
                msg.obj = value-1000;

                if(value &gt; 0)&#123;
                    //大于0时继续倒计时,循环发送消息
                    sendMessageDelayed(msg,1000);
                &#125;
                break;
        &#125;

    &#125;
&#125;
</code></pre>
<h2 id="-6"><a href="#-6" class="headerlink" title="}"></a>}</h2><h2 id="Service"><a href="#Service" class="headerlink" title="Service"></a>Service</h2><p>在后台长时间工作的应用主件,不会提供一个用户界面<br>不是单独的进程,也不是线程, 不能做耗时操作,需要new一个线程才可以做耗时操作<br>两种形式: start,stop  bind,unbind</p>
<p>public class MusicServiceActivity extends Activity implements View.OnClickListener {</p>
<pre><code>private Button mStartButton;
private Button mStopButton;
private MusicService mMusicService;
private ServiceConnection mServiceConnection = new ServiceConnection() &#123;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) &#123;
        //通过Binder获取了Service
        MusicService.localBinder locaBinder = (MusicService.localBinder) service;
        mMusicService = locaBinder.getService();
        if(mMusicService != null)&#123;
            int progress = mMusicService.getMusicPlayProgress();
        &#125;
    &#125;

    @Override
    public void onServiceDisconnected(ComponentName name) &#123;

    &#125;
&#125;;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_music_service);

    mStartButton = findViewById(R.id.start_button);
    mStopButton = findViewById(R.id.stop_button);

    mStartButton.setOnClickListener(this);
    mStopButton.setOnClickListener(this);


&#125;

@Override
public void onClick(View v) &#123;
    switch(v.getId())&#123;
        case R.id.start_button:
            //启动服务
            startService(new Intent(MusicServiceActivity.this,MusicService.class));
            //bind绑定
            bindService(new Intent(MusicServiceActivity.this,MusicService.class),mServiceConnection,BIND_AUTO_CREATE);


            break;
        case R.id.stop_button:
            //如果使用了bind绑定,直接stop就停不掉了,要先解绑
            unbindService(mServiceConnection);
            //停止服务
            stopService(new Intent(MusicServiceActivity.this,MusicService.class));
            break;
    &#125;
&#125;
</code></pre>
<p>}</p>
<hr>
<p>IntentService<br>如果想要任务按队列运行,就用IntentService</p>
<hr>
<p>public class TestIntentService extends IntentService {<br>    &#x2F;**<br>     * Creates an IntentService.  Invoked by your subclass’s constructor.<br>     *<br>     * @param name Used to name the worker thread, important only for debugging.<br>     *&#x2F;<br>    public TestIntentService(String name) {<br>        super(name);<br>    }</p>
<pre><code>@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) &#123;
    //不能做太多操作, UI线程  如果&gt;10秒 --&gt; ANR application not response 应用无响应

    //如果想做耗时操作,需要新建一个进程
    Thread thread = new Thread(new Runnable() &#123;
        @Override
        public void run() &#123;

        &#125;
    &#125;);

    thread.start();

    return super.onStartCommand(intent, flags, startId);
&#125;

@Override
protected void onHandleIntent(@Nullable Intent intent) &#123;
    // 排队 --&gt; 向MessageQueue 同步操作: 排队领书,处理Intent数据

&#125;
</code></pre>
<h2 id="-7"><a href="#-7" class="headerlink" title="}"></a>}</h2><h2 id="Broadcast"><a href="#Broadcast" class="headerlink" title="Broadcast"></a>Broadcast</h2><p>四大组件之一，广播接收器</p>
<p>系统使用了很多广播<br>    通知时间改变<br>    电池电量变低<br>    拍摄了照片<br>    改变了语言<br>没有用户界面<br>extends BroadcastReceiver</p>
<p>需要注册，有两种注册方式<br>    1. 静态注册<br>        在manifest里注册</p>
<pre><code>    &lt;receiver android:name=&quot;.TestBroadcastReceiver&quot;&gt;
        &lt;intent-filter&gt;
            &lt;action android:name=&quot;com.example.sqtian.broadcast&quot;/&gt;
        &lt;/intent-filter&gt;
    &lt;/receiver&gt;
2. 动态注册
    在代码里注册
public class SendBroadcastActivity extends Activity &#123;

    private  TestBroadcastReceiver mTestBroadcastReceiver = new TestBroadcastReceiver();
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
        super.onCreate(savedInstanceState);

        //动态注册广播
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction(&quot;com.example.sqtian.broadcast&quot;);
        registerReceiver(mTestBroadcastReceiver,intentFilter);
        
    &#125;
&#125;
</code></pre>
<p>BroadcastReceiver生命周期<br>Register<br>SendBroadcast<br>onReceive<br>unRegister</p>
<p>适当的用，不能滥用广播<br>信息需要很多地方都收到时，可以用</p>
<hr>
<p>public class SendBroadcastActivity extends Activity {</p>
<pre><code>public static final String COM_EXAMPLE_SQTIAN_BROADCAST = &quot;com.example.sqtian.broadcast&quot;;
private  TestBroadcastReceiver mTestBroadcastReceiver = new TestBroadcastReceiver();
private Button mSendBroadcastButton;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_broadcast);



    //获取broadcastButton

    mSendBroadcastButton = (Button) findViewById(R.id.send_broadcast_button);

    mSendBroadcastButton.setOnClickListener(new View.OnClickListener() &#123;
        @Override
        public void onClick(View v) &#123;
            Intent intent = new Intent();
            intent.setAction(COM_EXAMPLE_SQTIAN_BROADCAST);
            intent.putExtra(&quot;toast&quot;,&quot;this is my toast of broadcast&quot;);

            //普通广播
            sendBroadcast(intent);
</code></pre>
<p>&#x2F;&#x2F;                &#x2F;&#x2F;有序广播,有优先级的,类似intentService<br>&#x2F;&#x2F;                sendOrderedBroadcast()</p>
<p>&#x2F;&#x2F;                &#x2F;&#x2F;本地广播,只在本应用中的广播<br>&#x2F;&#x2F;                LocalBroadcastManager</p>
<pre><code>        &#125;
    &#125;);
&#125;


//在onstart中动态注册
@Override
protected void onStart() &#123;
    super.onStart();
    //动态注册广播
    IntentFilter intentFilter = new IntentFilter();

    intentFilter.addAction(COM_EXAMPLE_SQTIAN_BROADCAST);
    registerReceiver(mTestBroadcastReceiver,intentFilter);

&#125;

//在onStop中反注册


@Override
protected void onStop() &#123;
    super.onStop();
    unregisterReceiver(mTestBroadcastReceiver);
&#125;
</code></pre>
<h2 id="-8"><a href="#-8" class="headerlink" title="}"></a>}</h2><h2 id="D-ASWork-app-src-main-res-layout-activity-test-broadcast-xml"><a href="#D-ASWork-app-src-main-res-layout-activity-test-broadcast-xml" class="headerlink" title="D:\ASWork\app\src\main\res\layout\activity_test_broadcast.xml    
        "></a>D:\ASWork\app\src\main\res\layout\activity_test_broadcast.xml<br>    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BroadcastButton"
        android:id="@+id/send_broadcast_button"/>
        </h2><p>public class TestBroadcastReceiver extends BroadcastReceiver {<br>    @Override<br>    public void onReceive(Context context, Intent intent) {<br>        &#x2F;&#x2F; receive broadcast 接收,处理数据</p>
<pre><code>    //之间不能做耗时操作,new一个线程
    if(intent != null)&#123;
        if(TextUtils.equals(intent.getAction(),SendBroadcastActivity.COM_EXAMPLE_SQTIAN_BROADCAST))&#123;
            String toastString = intent.getStringExtra(&quot;tot&quot;);
            Toast.makeText(context,toastString,Toast.LENGTH_LONG).show();
        &#125;
    &#125;
&#125;
</code></pre>
<p>}</p>
<hr>
<h2 id="WebView：加载网页"><a href="#WebView：加载网页" class="headerlink" title="WebView：加载网页"></a>WebView：加载网页</h2><p>网页显示器<br>用处：<br>    加载线上url<br>    加载本地html<br>    和JS进行交互<br>    历史记录<br>    导航</p>
<p>要在manifest中声明权限 <uses-permission android:name="android.permission.INTERNET"/></p>
<hr>
<p>public class WebViewButtonActivity extends Activity {</p>
<pre><code>private WebView mWebView;

public class TestJSEvent&#123;
    @JavascriptInterface
    public void showToast(String toast)&#123;
        Toast.makeText(WebViewButtonActivity.this,toast,Toast.LENGTH_LONG).show();

    &#125;

&#125;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) &#123;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    mWebView = (WebView) findViewById(R.id.web_view);
    mWebView.loadUrl(&quot;http://www.baidu.com&quot;);
</code></pre>
<p>&#x2F;&#x2F;        &#x2F;&#x2F; 加载自己的html<br>&#x2F;&#x2F;        mWebView.loadUrl(“file:&#x2F;&#x2F;&#x2F;android_asset&#x2F;HelloWorld.html”);</p>
<pre><code>    //从百度页面跳转到别的页面,需要与JavaScript交互,打开才可以跳转
    mWebView.getSettings().setJavaScriptEnabled(true);
    //JS调用原生App方法showToast,即在HelloWorld.html里调用应用里的方法
    mWebView.addJavascriptInterface(new TestJSEvent(),&quot;TestApp&quot;);
</code></pre>
<p>&#x2F;&#x2F;        &#x2F;&#x2F;原生App调用JS<br>&#x2F;&#x2F;        mWebView.loadUrl(“javascript:(html里方法的名称)”);</p>
<pre><code>    //让页面在应用内部打开
    mWebView.setWebViewClient(new WebViewClient()&#123;
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) &#123;
            //是否要重新加载(拦截页面
            //比如一开始访问的网页失效了,404页面,可以重新加载一个页面
            if(url.contains(&quot;404&quot;))&#123;
                mWebView.loadUrl(&quot;http://www.zhihu.com&quot;);
            &#125;

            return super.shouldOverrideUrlLoading(view, url);
        &#125;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) &#123;
            //页面开始时,可以设置loading动画
            super.onPageStarted(view, url, favicon);
        &#125;

        @Override
        public void onPageFinished(WebView view, String url) &#123;
            //页面完成后,隐藏的loading动画
            super.onPageFinished(view, url);
        &#125;
    &#125;);
</code></pre>
<p>&#x2F;&#x2F;        mWebView.setWebChromeClient(new WebChromeClient(){<br>&#x2F;&#x2F;            @Override<br>&#x2F;&#x2F;            public void onProgressChanged(WebView view, int newProgress) {<br>&#x2F;&#x2F;                &#x2F;&#x2F;进度条<br>&#x2F;&#x2F;                super.onProgressChanged(view, newProgress);<br>&#x2F;&#x2F;            }<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;            @Override<br>&#x2F;&#x2F;            public void onReceivedTitle(WebView view, String title) {<br>&#x2F;&#x2F;                &#x2F;&#x2F; 获取界面的title<br>&#x2F;&#x2F;                super.onReceivedTitle(view, title);<br>&#x2F;&#x2F;            }<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;            @Override<br>&#x2F;&#x2F;            public void onShowCustomView(View view, CustomViewCallback callback) {<br>&#x2F;&#x2F;                super.onShowCustomView(view, callback);<br>&#x2F;&#x2F;            }<br>&#x2F;&#x2F;        });</p>
<pre><code>&#125;

//让返回时不会直接退出,而是返回上一网页
@Override
public void onBackPressed() &#123;

    if(mWebView != null &amp;&amp; mWebView.canGoBack())&#123;
</code></pre>
<p>&#x2F;&#x2F;            &#x2F;&#x2F;导航<br>&#x2F;&#x2F;            WebBackForwardList webBackForwardList &#x3D; mWebView.copyBackForwardList();<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;            WebHistoryItem historyItem &#x3D; webBackForwardList.getItemAtIndex(0);<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;            String historyUrl &#x3D; historyItem.getUrl();</p>
<pre><code>        //回退
        mWebView.goBack();
</code></pre>
<p>&#x2F;&#x2F;            &#x2F;&#x2F;前进<br>&#x2F;&#x2F;            mWebView.goForward();</p>
<pre><code>    &#125;else&#123;
        super.onBackPressed();
    &#125;

&#125;
</code></pre>
<p>}</p>
<hr>
<pre><code>&lt;WebView
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:id=&quot;@+id/web_view&quot;/&gt;
</code></pre>
<hr>
<p>更深入的使用：<br>    Cookie<br>    History<br>    页面导航<br>    Hybird<br>    如何拦截网络请求<br>    如何显示进度<br>    调试<br>    ……</p>
<h2 id="Widget"><a href="#Widget" class="headerlink" title="Widget"></a>Widget</h2><p>相当于挂件<br>从一个小Demo做起<br>首先新建一个TestWidget extends AppWidgetProvider<br>在AndroidManifest中声明TestWidget<br>在xml目录定义App Widget的初始化xml文件 setting_widget.xml<br>实现Widget具体布局的widget_layout.xml<br>继承AppWidgetProvider类，实现具体的Widget业务逻辑</p>
<p>public class TestWidget extends AppWidgetProvider {<br>    public static final String WIDGET_BUTTON_ACTION &#x3D; “widget_button_action”;<br>    &#x2F;&#x2F;桌面上的插件和应用需要通信，因此使用了广播机制，AppWidgetProvider extends BroadcastReceiver<br>    &#x2F;&#x2F;广播需要注册，因此Widget也需要注册</p>
<pre><code>@Override
public void onReceive(Context context, Intent intent) &#123;
    super.onReceive(context, intent);

    //intent不为空且action一致时接收广播信息
    if(intent != null &amp;&amp; WIDGET_BUTTON_ACTION.equals(intent.getAction()))&#123;
        Log.i(WIDGET_BUTTON_ACTION,&quot;be clicked&quot;);

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
        remoteViews.setTextViewText(R.id.widget_text_view,&quot;be clicked&quot;);
        remoteViews.setTextColor(R.id.widget_text_view, Color.BLUE);

        //获取appWidgetManager.updateAppWidget更新控件
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        //没有appWidgetIds,用另一个传ComponentName的方法
        ComponentName componentName = new ComponentName(context,TestWidget.class);
        appWidgetManager.updateAppWidget(componentName,remoteViews);

    &#125;
&#125;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) &#123;
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);

    Intent intent = new Intent();
    intent.setClass(context,TestWidget.class);
    intent.setAction(WIDGET_BUTTON_ACTION);

    //未来意图,将要执行的intent,点击以后才会发送广播
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,0);
    remoteViews.setOnClickPendingIntent(R.id.widget_button,pendingIntent);

    //更新控件
    appWidgetManager.updateAppWidget(appWidgetIds,remoteViews);
&#125;
</code></pre>
<p>}</p>
<hr>
<p>&lt;appwidget-provider xmlns:android&#x3D;”<a target="_blank" rel="noopener" href="http://schemas.android.com/apk/res/android&quot;">http://schemas.android.com/apk/res/android&quot;</a><br>    android:layout_width&#x3D;”match_parent”<br>    android:layout_height&#x3D;”match_parent”<br>    android:minWidth&#x3D;”140dp”<br>    android:minHeight&#x3D;”140dp”<br>    android:previewImage&#x3D;”@drawable&#x2F;cc1”                   &#x2F;&#x2F;预览的图片<br>    android:updatePeriodMillis&#x3D;”200000”                    &#x2F;&#x2F;更新周期<br>    android:widgetCategory &#x3D; “home_screen”                 &#x2F;&#x2F;挂件安装地点<br>    android:initialLayout&#x3D;”@layout&#x2F;widget_layout”&gt;</p>
</appwidget-provider>
--------------------------------------------------------------------------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

<pre><code>&lt;TextView
    android:id=&quot;@+id/widget_text_view&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_gravity=&quot;center&quot;
    android:text=&quot;TextView&quot; /&gt;

&lt;Button
    android:id=&quot;@+id/widget_button&quot;
    android:layout_gravity=&quot;center&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;Button&quot; /&gt;
</code></pre>
</LinearLayout>
--------------------------------------------------------------------------------------
    
<p>其他<br>与service通信<br>Widget控件的交互方法<br>如何做一个桌面播放器Widget</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/shiqing/about" rel="external nofollow noreferrer">ShiQing</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shiqing.gitee.io/shiqing/2020/04/17/androidpart1/">https://shiqing.gitee.io/shiqing/2020/04/17/androidpart1/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/shiqing/about" target="_blank">ShiQing</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/shiqing/tags/%E5%AE%89%E5%8D%93%E5%BC%80%E5%8F%91/">
                                    <span class="chip bg-color">安卓开发</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/shiqing/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/shiqing/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/shiqing/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/shiqing/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/shiqing/2020/04/19/java-ji-chu/javawebnote01-html/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/19.jpg" class="responsive-img" alt="&#39;JavaWebNote01_HTML&#39;">
                        
                        <span class="card-title">&#39;JavaWebNote01_HTML&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            web概念概述* JaveWeb：
    使用Java语言开发基于互联网的项目

* 软件架构
    1. C/S：客户端/服务器端
        在用户本地有一个客户端，在远程有一个服务器端
        如qq，迅雷
     
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-04-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/JavaWeb/">
                        <span class="chip bg-color">JavaWeb</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/shiqing/2020/04/06/java-ji-chu/javanote12-jdbcdatesource/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/8.jpg" class="responsive-img" alt="&#39;JavaNote12_JDBCDateSource&#39;">
                        
                        <span class="card-title">&#39;JavaNote12_JDBCDateSource&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            数据库连接池
概念：其实就是一个容器（集合），存放数据库连接的容器 当系统初始化好后，容器被创建，容器中会申请一些连接对象，当用户来访问数据库时， 从容器中获取连接对象，用户访问完之后，会将连接对象归还给容器

好处： 1. 节约资源 2.
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-04-06
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                        <span class="chip bg-color">Java基础</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/shiqing/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/shiqing/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




        <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/shiqing/about" target="_blank">ShiQing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2528393970@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2528393970" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2528393970" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/shiqing/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/shiqing/search.xml', 'searchInput', 'searchResult');
});
</script>

        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


        <script src="/shiqing/libs/materialize/materialize.min.js"></script>
        <script src="/shiqing/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/shiqing/libs/aos/aos.js"></script>
        <script src="/shiqing/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/shiqing/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/shiqing/js/matery.js"></script>

        <!-- Baidu Analytics -->

        <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

        
        <script src="/shiqing/libs/others/clicklove.js" async="async"></script>
        
        
        <script async src="/shiqing/libs/others/busuanzi.pure.mini.js"></script>
        

        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我~看不见我~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 背景樱花飘落特效 -->
        
            <script type="text/javascript">
                //只在桌面版网页启用特效
                var windowWidth = $(window).width();
                if (windowWidth > 768) {
                    document.write('<script type="text/javascript" src="/js/xuehuapiaoluo.js"><\/script>');
                }
            </script>
        

        

        


        
        

        

        

        
        <script src="/shiqing/libs/instantpage/instantpage.js" type="module"></script>
        

    </body>

</html>
